package com.dhcc.core.framework.security.client.wechat;

import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.modules.system.cache.user.UserCache;
import com.dhcc.core.modules.system.entity.User;
import org.apache.shiro.authc.CredentialsException;
import org.pac4j.core.context.Pac4jConstants;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.credentials.authenticator.Authenticator;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.core.util.CommonHelper;
import org.pac4j.oauth.credentials.OAuth20Credentials;
import org.pac4j.oauth.profile.wechat.WechatProfile;

public class WechatAuthenticator implements Authenticator<OAuth20Credentials> {
    @Override
    public void validate(OAuth20Credentials oAuth20Credentials, WebContext webContext) {
        //将获取到的userinfo跟库里的内容做比对，通过则返回校验成功
       WechatProfile wechatProfile= (WechatProfile) oAuth20Credentials.getUserProfile();
       if(CommonUtil.isNotEmpty(wechatProfile)){
           //已经获取profile说明成功获取用户信息
           String wxUsername = wechatProfile.getUsername();
           String wxUserId = wechatProfile.getId();
           if (CommonHelper.isBlank(wxUsername)||CommonHelper.isBlank(wxUserId)) {
               throw new CredentialsException("微信登录失败：不存在的用户！");
           }
           User user = UserCache.me().getUserByCode(wxUserId);
           if(CommonUtil.isNotEmpty(user)){
               // 生成user profile
               final CommonProfile profile = new CommonProfile();
               profile.setId(user.getName());
               profile.addAttribute(Pac4jConstants.USERNAME, user.getName());
               oAuth20Credentials.setUserProfile(profile);
           }
       }else{
           throw new CredentialsException("微信登录失败；未获取授权！");
       }
    }
}
